import datetime

import random
import string
import uuid
from random import Random

import os
from django.core.mail import send_mail
import json
from django.shortcuts import render, redirect, render_to_response
from django.http import HttpResponse, JsonResponse
# Create your views here.
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from Janebook import settings

from django.contrib.auth.hashers import make_password, check_password
from books import models
from books.models import User, Article, CommentInfo


def index(request):
    datas = Article.objects.all()[0:page_size]
    page_index=1
    return render_to_response('books/index.html',locals())

def detail(request,nid):
    articledetail=Article.objects.get(id=nid)
    return render(request,'books/articledetail.html',{'detail':articledetail})

def get_index_more(request):
    page_index=request.GET.get("page_index")
    article_list=indexpage(page_index)
    if len(article_list)>0:
        result_dict={"status":"ok","pageindex":int(page_index)+1,"data":article_list}
    else:
        result_dict={"status":"no"}
    return JsonResponse(json.dumps(result_dict),safe=False)

page_size=settings.PAGE_SIZE
def indexpage(page_index=0):
    start=int(page_index) *page_size
    end=int(start)+int(page_size)
    return list(Article.objects.all()[start:end].
                values("id","title","author","abstract","reply_num","read_num","like_num"))

def register(request):
    button = "发送验证码"
    err_msg = ''
    if request.method == "get":
        return render(request, 'books/register.html')
    nname = request.POST.get("nname")
    if (User.objects.filter(nickname=nname).count() > 0 and nname is None):
        return render(request, 'books/register.html', {"err_msg": "用户名已存在"})

    logphone = request.POST.get("phone")
    if (User.objects.filter(phone=logphone).count() > 0):
        return render(request, 'books/register.html', {"err_msg": "该手机号已注册"})

    logemail = request.POST.get("email")
    re_email = r'()@(qq)\.(com)'
    if User.objects.filter(email=logemail).count() > 0:
        return render(request, 'books/register.html', {"err_msg": "该邮箱已使用"})
    pwd = request.POST.get("pwd")
    pwd2 = request.POST.get("#confrim_pwd")
    if pwd != pwd2:
        return render(request, 'books/register.html', {"err_msg": "两次密码不一致！"})
    print(nname, logphone, logemail, pwd)

    user = User()
    user.nickname = nname
    user.phone = logphone
    user.email = logemail
    user.password = make_password(pwd)

    user.save()
    user.password = make_password(user.password)


    return render(request, 'books/login.html')


def registers(request):
    return render(request, 'books/register.html')


def chk_n_name(request):
    nname = request.GET.get("nick")
    user_list = User.objects.filter(nickname=nname)

    result = "no" if user_list.count() > 0 else "ok"
    return JsonResponse({"result": result})


def login(request):
    return render(request, 'books/login.html')


def logins(request):
    if request.session.get('is_login',None):
        return render(request,'books/index.html',locals())

    err_msg = ''
    if request.method == "POST":
        lphone = request.POST.get("phone_or_email")
        lpassword = request.POST.get("logpwd")
        lemail = request.POST.get("phone_or_email")
        uphone = User.objects.get(phone=lphone)
        name=uphone.nickname
        ps = uphone.password
        if check_password(lpassword, ps):
            request.session['is_login']=True
            request.session['user_name']=name
            datas = Article.objects.all()[0:page_size]
            page_index = 1
            return render_to_response('books/index.html', locals())
        else:
            err_msg = '用户名或密码错误，请重新输入!'
            return render(request, 'books/login.html', {'err_msg': err_msg})
    return render(request,'books/login.html')

def loginout(request):
    if not request.session.get('is_login',None):
        return render(request,'books/index.html',locals())
    request.session.flush()
    datas = Article.objects.all()[0:page_size]
    page_index = 1
    return render_to_response('books/index.html', locals())


def check_email(request):
    checktext=''
    checktexts=string.ascii_letters+string.digits
    for i in range(4):
        checktext += random.choice(checktexts)

    message ='您好！欢迎使用邮箱验证！您的邮箱验证码为：' + str(checktext)
    youMail=[request.GET.get('email')]
    send_mail(
        '简书邮箱注册验证码',
        message,
        settings.EMAIL_HOST_USER,
        list(youMail),
        fail_silently=False,
    )
    request.session['VCode'] = checktext
    return JsonResponse({'check':checktext})

@csrf_exempt
def upload_image(request):
    allow_suffix=['jpg','png','jpeg','gif']
    files=request.FILES.get("imgFile",None)
    if files:
        file_suffix=files.name.split(".")[-1]
        if file_suffix not in allow_suffix:
            return JsonResponse({"error":1,"message":"图片格式不正确"})
        file_name=str(uuid.uuid1())+"."+file_suffix
        file_path=os.path.join(settings.MEDIA_ROOT,'image',file_name)
        url_path=os.path.join(settings.MEDIA_URL,'image',file_name)
        with open(file_path, 'wb') as f:
            f.write(files.file.read())
        return JsonResponse({"error":0,"url":url_path})



def comment(request):
    user_id=request.session.get("user_id")
    if (id==None):
        return render_to_response({"url":reverse("login")})
    a_id=request.POST.get("id")
    a_content=request.POST.get("txt")
    comment=CommentInfo()
    comment.user=User.objects.get(id=user_id)
    comment.article=Article.objects.get("txt")
    comment.content=a_content
    comment.save()
    return JsonResponse({"stasus":"ok"})














